package com.gitee.mrj.aiboot.core.sf.generators.type;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gitee.mrj.aiboot.annotation.config.SFFormat;
import com.gitee.mrj.aiboot.annotation.config.sf.type.AlainString;
import com.gitee.mrj.aiboot.core.sf.generators.FormDefinitionGenerator;
import com.gitee.mrj.aiboot.core.sf.generators.UIForm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class AlainStringGenerator implements FormDefinitionGenerator {
    @Override
    public void generate(UIForm root, Field field, UIForm node) {
        AlainString alainField = AnnotatedElementUtils.findMergedAnnotation(field, AlainString.class);
        ObjectNode schema = node.getSchema();
        node.getUi().put("widget", SFSchemaType.STRING.toString());
        putInt(schema, "maxLength", alainField.maxLength());
        putInt(schema, "minLength", alainField.minLength());

        if (StringUtils.isNotBlank(alainField.pattern())) {
            schema.put("pattern", alainField.pattern());
        }
        if (!SFFormat.NULL.equals(alainField.format())) {
            schema.put("format", alainField.format().value());
        }
        schema.put("type", SFSchemaType.STRING.toString());
    }

    @Override
    public Class[] supports() {
        return new Class[]{AlainString.class};
    }
}
